import type { App } from "vue";

import { useIntersectionObserver } from "@vueuse/core";
// 默认图片
import defaultImg from "@/assets/logo.png";

export async function imgDirective(app: App) {
  // 1. v-lazy='xxx' 
  // 注意：指令名不加上 v- ，使用时 v-开头： v-lazy
  app.directive("lazy", {
    mounted(el, binding) {
      const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
        // isIntersecting 用于判断el元素是否进入可视区
        if (isIntersecting) {
          el.src = binding.value;
          // 错误回调 显示默认图片
          el.onerror = function () {
            this.src = defaultImg;
          };
          stop();
        }
      });
    },
  });
}
